import React, { useState } from 'react';

/**
 * 当条件符合时才执行, 且执行一次函数, 函数返回的值当做结果缓存下来
 * @param fn
 * @param condition
 * @returns {*[]}
 */
export default function useOnceByCondition(fn, condition) {
    const [data, setData] = React.useState(null);
    const [isChanged, setIsChanged] = useState();

    if (!isChanged) {
        if (condition instanceof Function ? condition() : condition) {
            setData(fn());
            setIsChanged(true);
        }
    }

    return data;
}
